import { ref } from 'vue'

/**
 * 加载状态管理的组合式函数
 */
export function useLoading() {
  // 动态导入 store 避免循环依赖
  const getAppStore = () => {
    const { useAppStore } = require('@/stores/app')
    return useAppStore()
  }
  const localLoading = ref(false)

  // 显示加载
  const showLoading = (title = '加载中...', useGlobal = false) => {
    if (useGlobal) {
      getAppStore().showLoading(title)
    } else {
      localLoading.value = true
      uni.showLoading({
        title,
        mask: true
      })
    }
  }

  // 隐藏加载
  const hideLoading = (useGlobal = false) => {
    if (useGlobal) {
      getAppStore().hideLoading()
    } else {
      localLoading.value = false
      uni.hideLoading()
    }
  }

  // 显示提示
  const showToast = (title, icon = 'none', duration = 2000) => {
    uni.showToast({
      title,
      icon,
      duration
    })
  }

  // 显示确认框
  const showModal = (title = '提示', content, showCancel = true) => {
    return new Promise((resolve) => {
      uni.showModal({
        title,
        content,
        showCancel,
        success: (res) => {
          resolve(res.confirm)
        }
      })
    })
  }

  return {
    loading: localLoading,
    showLoading,
    hideLoading,
    showToast,
    showModal
  }
}